
import { IRequestConfig } from '@/types';
import axios, { AxiosInstance } from 'axios';
import { httpInterceptor } from './interceptor';
import { IInterceptor } from './type';

/**
 * 服务端链接
 */
const backendUrl = '/api';

/**
 * http request client
 */
export class RequestClient {
     private _axios: AxiosInstance;
 
     constructor() {
         this._axios = axios.create({
             baseURL: backendUrl,
             timeout: 600000,
             headers: {'X-Custom-Header': 'foobar'}
         });
        httpInterceptor.forEach(int => {
            this.addInterceptor(int);
        });
     }
 
     /**
      * get请求
      * @param path 请求路径
      * @param conf 配置
      * @returns 
      */
     get(path: string, conf?: IRequestConfig): Promise<any> {
         return this._axios.get(
             path,
             conf
         );
     }
 
     /**
      * post请求
      * @param path 请求路径
      * @param data 请求数据
      * @returns 
      */
     post(path: string, data?: any, config?:any): Promise<any> {
         return this._axios.post(
             path,
             data,
             config
         );
     }
    /**
     * patch请求
     * @param path 请求路径
     * @param data 请求数据
     * @returns 
     */
    patch(path: string, data?: any): Promise<any> {
        return this._axios.patch(
            path,
            data
        );
    }
 
     /**
      * delete请求
      * @param path 请求路径
      * @param conf 配置
      * @returns 
      */
    delete(path: string, conf?: IRequestConfig): Promise<any> {
        return this._axios.delete(
            path,
            conf
        );
     }
 
     /**
      * 新增拦截器
      * @see http://axios-js.com/zh-cn/docs/index.html#%E6%8B%A6%E6%88%AA%E5%99%A8
      * @param int.request 请求拦截器
      * @param int.response 响应拦截器
      */
     addInterceptor(int: IInterceptor) {
         if (int.request) {
             this._axios.interceptors.request.use(int.request);
         }
         if (int.response) {
             this._axios.interceptors.response.use(int.response.onSuccess, int.response.onErr);
         }
     }
 }
 
/**
 * client singleton
 */
const requestClientSingleton = new RequestClient();

export {
    requestClientSingleton as requestClient
};

